<template>
  <el-dialog v-model="dialog.visible" title="活动管理" width="45%" @close="handleCloseDialog">
    <div class="form-container">
      <el-card shadow="never" class="table-card mb-[10px]">
        <el-form
          ref="baseFormRef"
          :model="formData"
          :rules="formRules"
          label-width="150px"
          class="form mb-0"
        >
          <el-form-item label="名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入名称" :maxlength="50"></el-input>
          </el-form-item>
          <el-form-item label="副标题" prop="title">
            <el-input
              v-model="formData.title"
              placeholder="请输入副标题"
              :maxlength="50"
            ></el-input>
          </el-form-item>
          <el-form-item label="活动内容" prop="content">
            <div style="height: calc(100vh - 500px); overflow: scroll" class="editor-box">
              <WangEditor v-model="formData.content" />
            </div>
            <!-- <el-input
              v-model="formData.content"
              type="textarea"
              placeholder="请输入活动内容"
              :maxlength="10000"
            ></el-input> -->
          </el-form-item>

          <el-form-item label="活动图片" prop="images">
            <MultiImageUpload v-model="formData.images" :limit="1" />
          </el-form-item>
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-model="formData.startTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择开始时间"
            />
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="formData.endTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择结束时间"
              @change=""
            />
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="handleCloseDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ElMessage } from "element-plus";
import MultiImageUpload from "@/components/Upload/MultiImageUpload.vue";
import ActivityAPI, { SysMerchantActivityForm } from "@/api/operationManage/activity";

// 定义 emit，用于通知外部关闭事件
const emit = defineEmits(["update:modelValue", "loadData"]);
const dialog = reactive({
  title: "",
  visible: false,
});
/*基础信息*/
const baseFormRef = ref();
const currentRow = ref({});

const defaultFormData: SysMerchantActivityForm = {
  content: "",
  endTime: "",
  id: undefined,
  images: [],
  name: "",
  remark: "",
  startTime: "",
  state: undefined,
  title: "",
};
const formData = ref({
  ...defaultFormData,
});
const formRules = reactive({
  content: [{ required: true, message: "请输入活动内容", trigger: "blur" }],
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  title: [{ required: true, message: "请输入副标题", trigger: "blur" }],
  images: [{ required: true, message: "请上传活动图片", trigger: "change" }],
  startTime: [{ required: true, message: "请选择开始时间", trigger: "change" }],
  endTime: [{ required: true, message: "请选择结束时间", trigger: "change" }],
});

async function handleSubmit() {
  const validate = await baseFormRef.value.validate();
  if (!validate) return;
  let sdate = new Date(formData.value.startTime);
  let edate = new Date(formData.value.endTime);
  let sTiem = sdate.getTime();
  let eTime = edate.getTime();
  if (sTiem > eTime) {
    ElMessage.error("开始时间不能大于结束时间");
    return;
  }
  try {
    if (formData.value.id) {
      await ActivityAPI.resubmit({
        ...formData.value,
        images: JSON.stringify(formData.value.images),
      });
    } else {
      await ActivityAPI.add({
        ...formData.value,
        images: JSON.stringify(formData.value.images),
      });
    }

    ElMessage.success("成功");
    emit("loadData");
    handleCloseDialog();
  } catch (error) {
    console.log("error", error);
    //ElMessage.error("失败");
  }
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  formData.value = {};
  Object.assign(formData.value, JSON.parse(JSON.stringify(defaultFormData)));
  emit("update:modelValue", false); // 关闭弹窗
}

function showModal(val) {
  dialog.visible = true;
  currentRow.value = val;
  if (val) {
    getDetailById(val.id);
  } else {
    Object.assign(formData.value, JSON.parse(JSON.stringify(defaultFormData)));
  }
}

async function getDetailById(id) {
  try {
    const data = await ActivityAPI.getDetailById({
      id,
    });
    const { images } = data || {};
    formData.value = {
      ...formData.value,
      ...defaultFormData,
      ...data,
      ...{
        images: JSON.parse(images || "[]"),
      },
    };
  } catch (e) {
    console.log(e);
  }
}

defineExpose({
  showModal,
});
</script>
<style style="scss" scoped>
.form-container {
  height: 600px;
  overflow: auto;
}
.form {
  ::v-deep(.el-form-item) {
    margin-bottom: 0;
  }
}
</style>
